// JavaScript Document
//*************************************************************************************
//
//   Google Maps Module v3 by breitsch (mail@casa-loca.com)
//
//*************************************************************************************

function wheelevent(e) {
  if (!e){
    e = window.event;
  }
  if (e.preventDefault){
    e.preventDefault();
  }
  e.returnValue = false;
}

function in_array(needle, haystack, strict) {
    var found = false, key, strict = !!strict;
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }
    return found;
}

function urlencode( str ) {                                 
    var ret = str;
    ret = ret.toString();
    ret = encodeURIComponent(ret);
    ret = ret.replace(/%20/g, "+");
    return ret;
}

function htmlentities( s ){
    var div = document.createElement('div');
    var text = document.createTextNode(s);
    div.appendChild(text);
    return div.innerHTML;
}

function html_entity_decode( string ) {
    var ret, tarea = document.createElement('textarea');
    tarea.innerHTML = string;
    ret = tarea.value;
    return ret;
}

function createXMLHttpRequest() {

var ua;

if(window.XMLHttpRequest) {
    try {
      ua = new XMLHttpRequest();
    } catch(e) {
      ua = false;
    }
  } else if(window.ActiveXObject) {
    try {
      ua = new ActiveXObject("Microsoft.XMLHTTP");
    } catch(e) {
      ua = false;
    }
  }
  return ua;
}

function printout(what,printWhat,path,expr) {
var txtFile = createXMLHttpRequest();
var myNewString = "";
var a = window.open("","","width=500,height=600,scrollbars=yes,location=no");
a.document.open();
txtFile.open("GET", path+"template/default/print_"+ what +".tmpl", true);
txtFile.onreadystatechange = function() {
  if (txtFile.readyState == 4) {  // Makes sure the document is ready to parse.
    if (txtFile.status == 200) {  // Makes sure it's found the file.
      var allText = txtFile.responseText
      myNewString = allText.replace("{LISTING}", document.getElementById(printWhat).innerHTML);
      a.document.write('<a id="printlink" href="javascript:window.print()">'+expr+'</a><br />' + myNewString);
		  a.document.close();
    }
  }
}
txtFile.send(null);
}

function Reposition(cpid,initzoom) {
  var map = window["map" + cpid];
  var gmarkers = window["gmarkers" + cpid];

  var MinX = 360; var MinY = 360;
  var MaxX = -360; var MaxY = -360;
  var MarkerCount = 0;
  gmarkers.for_Each(function(item, index) {
    var markera = gmarkers[index];
            if(markera.isHidden()) {
            } else {
                var l = markera.getLatLng();
                if (l.lat() < MinX)MinX = l.lat();
                if (l.lat() > MaxX)MaxX = l.lat();
                if (l.lng() < MinY)MinY = l.lng();
                if (l.lng() > MaxY)MaxY = l.lng();
                MarkerCount++;
            }
  });
  if(MarkerCount == 1) {
     map.setCenter(new google.maps.LatLng(MinX, MinY),initzoom);
  } else if(MarkerCount > 1) {
    var OffsetX=(MaxX-MinX)/8;
    var OffsetY = (MaxY-MinY)/8;
    var sw = new google.maps.LatLng(MinX-OffsetX,MinY-OffsetY);
    var ne = new google.maps.LatLng(MaxX+OffsetX,MaxY+OffsetY);
    var bounds = new google.maps.LatLngBounds(sw,ne);
    map.setZoom(map.getBoundsZoomLevel(bounds));
    map.panTo(bounds.getCenter());
  }
}

Array.prototype.for_Each = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var iw = 0; iw < len; iw++)
    {
      if (iw in this)
        fun.call(thisp, this[iw], iw, this);
    }
  };


function toggleGroup(type, actCatChecked, cpid,initzoom) {
  var lmarkers = window["lmarkers" + cpid];
  var markerGroups = window["markerGroups" + cpid];
  var searchactive = window["searchactive" + cpid]; 
  var search_markers = window["search_markers" + cpid];
  var sidebarEntry = window["sidebarEntry" + cpid];
  var stop_lmarkers_reset = window["stop_lmarkers_reset" + cpid];
  eval('lmarkers' + cpid + '.length = 0');
  var kmarkers = [];
    for (var index in markerGroups) {
      if (index != type){
        for (var y = 0; y < markerGroups[index].length; y++) {
          var marker2 = markerGroups[index][y];
           if (document.getElementById("cb_"+index).checked==true) kmarkers.push(marker2.getLatLng());         
          if (document.getElementById("cb_"+index).checked==false) eval('lmarkers' + cpid + '.push(marker2.getLatLng())');
        }
      } else {
        for (var y = 0; y < markerGroups[type].length; y++) {
          var marker3 = markerGroups[type][y];
            if (document.getElementById("cb_"+type).checked==false) eval('lmarkers' + cpid + '.push(marker3.getLatLng())');
            if (document.getElementById("cb_"+type).checked==true) kmarkers.push(marker3.getLatLng());
        }
      }
    }
    for (var index in markerGroups) {
    for (var iw = 0; iw < markerGroups[index].length; iw++) {
      var marker = markerGroups[index][iw]; 
      if (searchactive==true) {
        if (marker.isHidden() && in_array(marker.getLatLng(), search_markers) && in_array(marker.getLatLng(), kmarkers)) {
          marker.show();
          var changeInSearchlisting = true;
        } else if(!in_array(marker.getLatLng(), kmarkers)) {
          marker.hide();
          var changeInSearchlisting = true;
        }
      } else {
        if (marker.isHidden()) { 
          if (in_array(marker.getLatLng(), kmarkers)){
            marker.show();
          }
        } else {
          if (!in_array(marker.getLatLng(), kmarkers)){
            marker.hide();
          }
        }
      }
    }
  }
  if (changeInSearchlisting) {
    var sidebar = document.getElementById("gmsearch-result-"+cpid);
    sidebar.innerHTML = '';
    var searchLimit = search_markers.length;
    for (var z = 0; z < searchLimit; z++) {
      if(in_array(search_markers[z], kmarkers)){
        var bb = search_markers[z].replace(/\(/g, "");
        bb = bb.replace(/\)/g, "");
        bb = bb.replace(/\./g, "");
        bb = bb.replace(/\, /g, "");
        sidebarEntry[bb]["htmlEntry"].innerHTML=sidebarEntry[bb]["htmlhtml"];
        sidebar.appendChild(sidebarEntry[bb]["htmlEntry"]);
      } else if(!in_array(search_markers[z], lmarkers)){
        var bb = search_markers[z].replace(/\(/g, "");
        bb = bb.replace(/\)/g, "");
        bb = bb.replace(/\./g, "");
        bb = bb.replace(/\, /g, "");
        sidebarEntry[bb]["htmlEntry"].innerHTML=sidebarEntry[bb]["htmlhtml"];
        sidebar.appendChild(sidebarEntry[bb]["htmlEntry"]);
      }
    }
  }
  kmarkers.length=0;
  Reposition(cpid,initzoom); 
}

function check(chk,type,cpid,initzoom) {
  var my_form = "myform"+cpid;
  eval('stop_lmarkers_reset' + cpid + ' = 1');
  eval('lmarkers' + cpid + '.length = 0');
  var markerGroups = window["markerGroups" + cpid];
  var chkd = eval('document.' + my_form + '.elements');
  if(document.getElementById(type).checked==true){
    if (chkd.length) {
      for (iw = 0; iw < chkd.length; iw++) {
        if(chkd[iw].name=="cb_"+chk){
          chkd[iw].checked = true ;
        }
      }
      toggleGroup(chk, "true",cpid,initzoom);
    } else {
      var thisCheckID = chkd.value;
      toggleGroup(thisCheckID, "true",cpid,initzoom); 
      chkd.checked = true ;
    }
  } else {
    if (chkd.length) { 
      for (iw = 0; iw < chkd.length; iw++) {
        if(chkd[iw].name=="cb_"+chk){
          chkd[iw].checked = false ;
        }
      }
       toggleGroup(chk, "false",cpid,initzoom); 
    } else {
      chkd.checked = false ;
      var thisCheckID = chkd.value;
      toggleGroup(thisCheckID, "true",cpid,initzoom); 
    }
  }
  eval('stop_lmarkers_reset' + cpid + ' = 0');
}

function formatDirections(cpid) {
    var hz = document.getElementById("gmtab-container-"+cpid).offsetHeight;
    var ha = document.getElementById("gmnav-container-"+cpid).offsetHeight;
    var hb = document.getElementById("gmnav2-container-"+cpid).offsetHeight;
    document.getElementById("li-2-2-"+cpid).style.display="inline";
    document.getElementById("li-2-3-"+cpid).style.display="inline";
    document.getElementById("li-2-4-"+cpid).style.display="inline";
    document.getElementById("gmdirections"+cpid).style.height=(hz-ha-hb-20)+"px";
}

function clearrp(cpid) {
    var gdir = window["gdir" + cpid];
    gdir.clear();
    document.getElementById("li-2-2-"+cpid).style.display="none";
    document.getElementById("li-2-3-"+cpid).style.display="none";
    document.getElementById("li-2-4-"+cpid).style.display="none";
}

function searchLocations(cp_ids, srchin, cpid, kmmi, initzoom, langsys) {
    var searchactive = window["searchactive" + cpid];
    var txt =  document.getElementById("txtInput"+cpid).value;
    var address = document.getElementById("addressInput"+cpid).value;
    var radius = document.getElementById("radiusSelect"+cpid).value;
    eval('searchactive' + cpid + ' = true');
    if (address) {
      document.getElementById("gmsearch-result-"+cpid).style.display="none";
      document.getElementById("gmtab-search-wait"+cpid).style.display="block";
      var sWhat = "adress";
      geocoder.getLatLng(address, function(latlng) {
        if (!latlng) {
          alert(address + " not found");
        } else {
        if (radius==0) {
        	sWhat = "adressOnly";
          radius=1;
        }
          toggleSearch(encodeURIComponent(txt), latlng, radius, sWhat, cp_ids, srchin, cpid, kmmi, initzoom, langsys);
        }
      });
      return;
    }
    if (txt) {
      document.getElementById("gmsearch-result-"+cpid).style.display="none";
      document.getElementById("gmtab-search-wait"+cpid).style.display="block";
      var sWhat = "text";   
      var latlng = 0;
      radius = 0;
      
      toggleSearch(encodeURIComponent(txt), latlng, radius, sWhat, cp_ids, srchin, cpid, kmmi, initzoom, langsys);
      return;
    }
    eval('searchactive' + cpid + ' = false');
    return;
}  

function clear_search(cpid,initzoom,hideOnInit) {
  var searchactive = window["searchactive" + cpid];
  var gmarkers = window["gmarkers" + cpid];
  var lmarkers = window["lmarkers" + cpid];
  var map = window["map" + cpid];
  var MinX = 360; var MinY = 360;
  var MaxX = -360; var MaxY = -360;
  var MarkerCount = 0;
    var sidebar = document.getElementById("gmsearch-result-"+cpid);
    sidebar.innerHTML = '';
    eval('searchactive' + cpid + ' = false');
    gmarkers.for_Each(function(item, index) {
        var marker = gmarkers[index];
        if (marker.isHidden() && !in_array(marker.getLatLng(), lmarkers)) {
              if (hideOnInit==0) marker.show();
              var l = marker.getLatLng();
              if (l.lat() < MinX)MinX = l.lat();
              if (l.lat() > MaxX)MaxX = l.lat();
              if (l.lng() < MinY)MinY = l.lng();
              if (l.lng() > MaxY)MaxY = l.lng();
              MarkerCount++;                
        } else {
              var l = marker.getLatLng();
              if (l.lat() < MinX)MinX = l.lat();
              if (l.lat() > MaxX)MaxX = l.lat();
              if (l.lng() < MinY)MinY = l.lng();
              if (l.lng() > MaxY)MaxY = l.lng();
              MarkerCount++;
        }
    });    
    document.getElementById("txtInput"+cpid).value="";
    document.getElementById("addressInput"+cpid).value="";
    document.getElementById("radiusSelect"+cpid).value=0;
    document.getElementById("gmsearch-result-"+cpid).style.display="none";
    if(document.getElementById("gmcatinfo"+cpid)) document.getElementById("gmcatinfo"+cpid).style.display="none";
    document.getElementById("li-3-3-"+cpid).style.display="none";
    document.getElementById("li-3-4-"+cpid).style.display="none";
    if(MarkerCount == 1) {
      map.setCenter(new google.maps.LatLng(MinX, MinY), initzoom);
    } else if(MarkerCount > 1) {
      var OffsetX=(MaxX-MinX)/8;
      var OffsetY = (MaxY-MinY)/8;
      var sw = new google.maps.LatLng(MinX-OffsetX,MinY-OffsetY);
      var ne = new google.maps.LatLng(MaxX+OffsetX,MaxY+OffsetY);
      var bounds = new google.maps.LatLngBounds(sw,ne);
    map.setZoom(map.getBoundsZoomLevel(bounds));
    map.panTo(bounds.getCenter());
    }
}

function createSidebarEntry(name, addr, distance, pointid, kmmi, cpid) {
      var gmarkers = window["gmarkers" + cpid];
      var div = document.createElement("div");
      addr = html_entity_decode( addr );
      if (distance >=0) {
      var html = "<b>" + name + "</b> (" + distance.toFixed(1) + kmmi + ")<br/>" + addr;      
      } else {
      var html = "<b>" + name + "</b><br/>" + addr;
      }
      div.innerHTML = html;
      div.style.cursor = "pointer";
      div.style.marginBottom = "1px"; 
      GEvent.addDomListener(div, "click", function() {
        GEvent.trigger(gmarkers[pointid], "click");
      });
      var a = document.createAttribute("class");
      a.nodeValue="gmsearchHover";
      GEvent.addDomListener(div, "mouseover", function() {
        div.setAttributeNode(a);
      });
      var b = document.createAttribute("class");
      b.nodeValue="gmsearchDefault";      
      GEvent.addDomListener(div, "mouseout", function() {
        div.setAttributeNode(b);
      });
      div.setAttributeNode(b);
      return div;
}

function toggleSearch(txt, center, radius, sWhat, cp_ids, srchin, cpid, kmmi, initzoom, langsys) {
  toggleGroup(0, "true",cpid,initzoom);
  var search_markers = window["search_markers" + cpid];
  var gmarkers = window["gmarkers" + cpid];
  var lmarkers = window["lmarkers" + cpid];
  var amarkers = [];
  var sidebarEntry = window["sidebarEntry" + cpid];
  var map = window["map" + cpid];
  var MinX = 360; var MinY = 360;
  var MaxX = -360; var MaxY = -360;
  var MarkerCount = 0;
  var divf = document.createElement("div");  
  eval('search_markers' + cpid + '.length = 0');
  var gettxt = "";  
  if (sWhat=="text") {
    var searchUrl = 'include/inc_module/mod_googlemaps/phpsqlsearch_genxml.php?srch='+ srchin +'&sys='+ langsys +'&txt='+ txt +'&radius='+ radius +'&cpids='+ cp_ids;
  } else {
    if(txt){
      gettxt = "&txt="+ txt;
    }
    var searchUrl = 'include/inc_module/mod_googlemaps/phpsqlsearch_genxml.php?srch='+ srchin +'&sys='+ langsys +'&lat='+ center.lat() +'&lng='+ center.lng() +'&radius='+ radius +'&cpids='+ cp_ids + gettxt;  
  }  
  GDownloadUrl(searchUrl, function(data) {
    var xml = GXml.parse(data);
    var markers = xml.documentElement.getElementsByTagName("marker");
    var sidebar = document.getElementById("gmsearch-result-"+cpid);
    sidebar.innerHTML = '';
    if (markers.length == 0) {
      sidebar.appendChild(divf);
      divf.innerHTML = "No results found.";
      eval('searchactive' + cpid + ' = false');
      toggleGroup(0, "true",cpid,initzoom);
      document.getElementById("gmtab-search-wait"+cpid).style.display="none";
      document.getElementById("gmsearch-result-"+cpid).style.display="block";
      return;
    }        
    for (var y = 0; y < markers.length; y++) {
      var pointid = markers[y].getAttribute("pointid");
      var name = markers[y].getAttribute("name");
      var addr = markers[y].getAttribute("address");
      var distance = parseFloat(markers[y].getAttribute("distance"));
      var latlng = "("+markers[y].getAttribute("lat")+", "+markers[y].getAttribute("lng")+")";   
      eval('search_markers' + cpid + '.push(latlng)');
      var bb = latlng.replace(/\(/g, "");
      bb = bb.replace(/\)/g, "");
      bb = bb.replace(/\./g, "");
      bb = bb.replace(/\, /g, "");
      sidebarEntry[bb] = new Object();
      sidebarEntry[bb]["htmlEntry"] = createSidebarEntry(name, addr, distance, pointid, kmmi, cpid);
      sidebarEntry[bb]["htmlhtml"] = sidebarEntry[bb]["htmlEntry"].innerHTML;  
    }     
    gmarkers.for_Each(function(item, index) {
        var marker = gmarkers[index];
        if (marker.isHidden()) {
          if(in_array(marker.getLatLng(), search_markers) && !in_array(marker.getLatLng(), lmarkers)){
              marker.show();
              amarkers.push(marker.getLatLng());
              var l = marker.getLatLng();
              if (l.lat() < MinX)MinX = l.lat();
              if (l.lat() > MaxX)MaxX = l.lat();
              if (l.lng() < MinY)MinY = l.lng();
              if (l.lng() > MaxY)MaxY = l.lng();
              MarkerCount++;
          }
        } else {
          if(in_array(marker.getLatLng(), search_markers)){
              amarkers.push(marker.getLatLng());
              var l = marker.getLatLng();
              if (l.lat() < MinX)MinX = l.lat();
              if (l.lat() > MaxX)MaxX = l.lat();
              if (l.lng() < MinY)MinY = l.lng();
              if (l.lng() > MaxY)MaxY = l.lng();
              MarkerCount++;
          } else {
              marker.hide();
          }
        }
    });
    var searchLimit = search_markers.length; 
    for (var z = 0; z < searchLimit; z++) {
      if(in_array(search_markers[z], amarkers)){
        var bb = search_markers[z].replace(/\(/g, "");
        bb = bb.replace(/\)/g, "");
        bb = bb.replace(/\./g, "");
        bb = bb.replace(/\, /g, "");
        sidebar.appendChild(sidebarEntry[bb]["htmlEntry"]);
      }
    }
    if(MarkerCount == 1) {
      map.setCenter(new google.maps.LatLng(MinX, MinY), initzoom);
    } else if(MarkerCount > 1) {
      var OffsetX=(MaxX-MinX)/8;
      var OffsetY = (MaxY-MinY)/8;
      var sw = new google.maps.LatLng(MinX-OffsetX,MinY-OffsetY);
      var ne = new google.maps.LatLng(MaxX+OffsetX,MaxY+OffsetY);
      var bounds = new google.maps.LatLngBounds(sw,ne);
    map.setZoom(map.getBoundsZoomLevel(bounds));
    map.panTo(bounds.getCenter());
    }
  });
    var hz = document.getElementById("gmtab-container-"+cpid).offsetHeight;
    var ha = document.getElementById("gmnav-container-"+cpid).offsetHeight;
    var hb = document.getElementById("gmnav3-container-"+cpid).offsetHeight;
  var ee = document.getElementById("tabform3-"+cpid);
  var aa = (ee.currentStyle)?parseInt(ee.currentStyle.paddingTop):parseInt(window.getComputedStyle(ee,null).paddingTop);
  var ab = (ee.currentStyle)?parseInt(ee.currentStyle.marginTop):parseInt(window.getComputedStyle(ee,null).marginTop);
  var ac = (ee.currentStyle)?parseInt(ee.currentStyle.paddingBottom):parseInt(window.getComputedStyle(ee,null).paddingBottom);
  var ad = (ee.currentStyle)?parseInt(ee.currentStyle.marginBottom):parseInt(window.getComputedStyle(ee,null).marginBottom);
  var ae = (aa+ab+ac+ad);
    var hc = document.getElementById("tabform3-"+cpid).offsetHeight;
    document.getElementById("li-3-3-"+cpid).style.display="inline";
    document.getElementById("li-3-4-"+cpid).style.display="inline";
    document.getElementById("gmsearch-result-"+cpid).style.height=(hz-ha-hb-hc-ae-10)+"px";
    document.getElementById("gmtab-search-wait"+cpid).style.display="none";     
    document.getElementById("gmsearch-result-"+cpid).style.display="block";
    if(document.getElementById("gmcatinfo"+cpid)) document.getElementById("gmcatinfo"+cpid).style.display="block";
return true;
}